package salary.calculation.common.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class EasyExcelUtils {

    public static<T> List<T> read(MultipartFile file,Class<T> cls) throws IOException {
        Map<Integer, String> head = new HashMap<>();
        List<T> data = new LinkedList();
        EasyExcel.read(file.getInputStream(),cls,new AnalysisEventListener<T>() {
            @Override
            public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
                head.putAll(headMap);
            }

            @Override
            public void invoke(T bo, AnalysisContext analysisContext) {
                data.add(bo);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                System.out.print("解析完毕:"+data.size());
            }
        }).sheet().headRowNumber(2).doRead();
        return data;
    }

    public static<T> void write(OutputStream out, String sheetName, List<T> data, Class<T> cls, WriteHandler handler){
        ExcelWriter excelWriter = EasyExcel.write(out).excelType(ExcelTypeEnum.XLSX).build();
        WriteSheet writeSheet = EasyExcel.writerSheet(0,sheetName).head(cls)
                .registerWriteHandler(handler).build();
        excelWriter.write(data,writeSheet);
        excelWriter.finish();
    }

    public static<T> void write(File file, String sheetName, List<T> data, Class<T> cls, WriteHandler handler){
        ExcelWriter excelWriter = EasyExcel.write(file).excelType(ExcelTypeEnum.XLSX).build();
        WriteSheet writeSheet = EasyExcel.writerSheet(0,sheetName).head(cls)
                .registerWriteHandler(handler).build();
        excelWriter.write(data,writeSheet);
        excelWriter.finish();
    }

}
